"use client"

import { useEffect, useState } from "react"
import { Role } from "@/types/admin"
import { useAdminStore } from "@/lib/store"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"
import { Checkbox } from "@/components/ui/checkbox"

const formSchema = z.object({
  name: z.string().min(1, "角色名称不能为空"),
  description: z.string().min(1, "角色描述不能为空"),
  permissions: z.array(z.string()).min(1, "至少选择一个权限"),
})

type FormValues = z.infer<typeof formSchema>

interface RoleDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  role?: Role
}

// 所有可用的权限列表
const availablePermissions = [
  { id: "manage_users", label: "用户管理" },
  { id: "manage_roles", label: "角色管理" },
  { id: "manage_departments", label: "部门管理" },
  { id: "manage_tracks", label: "股道管理" },
  { id: "manage_templates", label: "操作票模板管理" },
  { id: "create_ticket", label: "创建操作票" },
  { id: "execute_ticket", label: "执行操作票" },
  { id: "approve_ticket", label: "审批操作票" },
  { id: "view_history", label: "查看历史记录" },
  { id: "view_dashboard", label: "查看仪表盘" },
]

export function RoleDialog({
  open,
  onOpenChange,
  role,
}: RoleDialogProps) {
  const { addRole, updateRole } = useAdminStore()
  const isEditing = !!role

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: role?.name || "",
      description: role?.description || "",
      permissions: role?.permissions || [],
    },
  })

  useEffect(() => {
    if (open) {
      if (role) {
        form.reset({
          name: role.name,
          description: role.description,
          permissions: role.permissions,
        })
      } else {
        form.reset({
          name: "",
          description: "",
          permissions: [],
        })
      }
    }
  }, [open, role, form])

  const onSubmit = (values: FormValues) => {
    const roleData = {
      name: values.name,
      description: values.description,
      permissions: values.permissions,
    }

    if (isEditing && role) {
      updateRole(role.id, roleData)
    } else {
      addRole(roleData)
    }

    onOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[550px]">
        <DialogHeader>
          <DialogTitle>{isEditing ? "编辑角色" : "新增角色"}</DialogTitle>
          <DialogDescription>
            {isEditing
              ? "修改角色信息和权限，点击保存确认更改。"
              : "添加新角色，设置角色名称、描述和权限。"}
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>角色名称</FormLabel>
                  <FormControl>
                    <Input placeholder="如：管理员、操作员" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>角色描述</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="描述该角色的职责和权限范围"
                      className="resize-none"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="permissions"
              render={() => (
                <FormItem>
                  <div className="mb-4">
                    <FormLabel>权限设置</FormLabel>
                  </div>
                  <div className="grid grid-cols-2 gap-2">
                    {availablePermissions.map((permission) => (
                      <FormField
                        key={permission.id}
                        control={form.control}
                        name="permissions"
                        render={({ field }) => {
                          return (
                            <FormItem
                              key={permission.id}
                              className="flex flex-row items-start space-x-3 space-y-0"
                            >
                              <FormControl>
                                <Checkbox
                                  checked={field.value?.includes(permission.id)}
                                  onCheckedChange={(checked) => {
                                    return checked
                                      ? field.onChange([...field.value, permission.id])
                                      : field.onChange(
                                          field.value?.filter(
                                            (value) => value !== permission.id
                                          )
                                        )
                                  }}
                                />
                              </FormControl>
                              <FormLabel className="font-normal">
                                {permission.label}
                              </FormLabel>
                            </FormItem>
                          )
                        }}
                      />
                    ))}
                  </div>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter>
              <Button type="submit">
                {isEditing ? "保存" : "创建"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}
